const _my = require("../../../../../__antmove/api/index.js")(my);
const wx = _my;
let WebIM = require("../../../../../utils/WebIM")["default"];
let msgType = require("../../../msgtype");
let disp = require("../../../../../utils/broadcast");
let backend = require("../../../../../utils/backend");
Component({
  properties: {
    username: {
      type: Object,
      value: {}
    },
    chatType: {
      type: String,
      value: msgType.chatType.SINGLE_CHAT
    },
    onWillSend:(data) =>{},
  },
  data: {
    inputMessage: "",
    // render input 的值
    userMessage: "", // input 的实时值
    promptId: '0'     // ai的promptId
  },
  methods: {
    focus() {
      this.triggerEvent("inputFocused", null, {
        bubbles: true
      });
    },
    blur() {
      this.triggerEvent("inputBlured", null, {
        bubbles: true
      });
    },
    isGroupChat() {
      return this.data.chatType == msgType.chatType.CHAT_ROOM;
    },
    getSendToParam() {
      return this.isGroupChat() ? this.data.username.groupId : this.data.username.your;
    },
    // bindinput 不能打冒号！
    bindMessage(e) {
      this.setData({
        userMessage: e.detail.value
      });
    },
    emojiAction(emoji) {
      var str;
      var msglen = this.data.userMessage.length - 1;
      if (emoji && emoji != "[del]") {
        str = this.data.userMessage + emoji;
      } else if (emoji == "[del]") {
        let start = this.data.userMessage.lastIndexOf("[");
        let end = this.data.userMessage.lastIndexOf("]");
        let len = end - start;
        if (end != -1 && end == msglen && len >= 3 && len <= 4) {
          str = this.data.userMessage.slice(0, start);
        } else {
          str = this.data.userMessage.slice(0, msglen);
        }
      }
      this.setData({
        userMessage: str,
        inputMessage: str
      });
    },
    sendMessage() {
      let me = this;
      String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, "");
      };
      if (!this.data.userMessage.trim()) {
        return;
      }
      let id = WebIM.conn.getUniqueId();
      let msg = new WebIM.message(msgType.TEXT, id);
      msg.set({
        msg: this.data.userMessage,
        from: this.data.username.myName,
        to: this.getSendToParam(),
        roomType: false,
        chatType: this.data.chatType,
        success(id, serverMsgId) {
          console.log("成功了");
          disp.fire("em.chat.sendSuccess", id, me.data.userMessage);
          me.triggerEvent("newTextMsg", {
            msg: msg,
            type: msgType.TEXT
          }, {
            bubbles: true,
            composed: true
          });
        },
        fail(id, serverMsgId) {
          console.log("失败了");
          console.log("id", id);
          console.log("serverMsgId", serverMsgId);
        }
      });
      if (this.data.chatType == msgType.chatType.CHAT_ROOM) {
        msg.setGroup("groupchat");
      }
      console.log('will send messge', msg.body);
      this.props.onWillSend(msg);
      WebIM.conn.send(msg.body).catch(err => {
        console.log("err", err);
        if (err.type === 507) {
          wx.showToast({
            title: "你已经被禁言",
            icon: "error",
            duration: 2000
          });
        }
      });
      // 后端处理逻辑
      console.log('当前输入内容', me.data.userMessage);
      var curInputMessage =  me.data.userMessage;
      if (this.isGroupChat()) {
        // 群聊
        if (curInputMessage.startsWith('/aibot')) {
          if (curInputMessage.startsWith('/aibot summary')) {
            var req = {
              groupId: this.getSendToParam()
            };
            backend.askForSummary(req);
          } else if(curInputMessage.startsWith('/aibot help')) {
            my.confirm({
              title: '温馨提示',
              content: '/aibot summary   获取群历史消息总结 \n'
                  +    '/aibot help      使用帮助 \n'
                  +    '/aibot addBot    添加机器人',
            });
          } else if(curInputMessage.startsWith('/aibot addBot')) {
            var req = {
              groupId: this.getSendToParam(),
              userId: 'user_Bot'
            };
            backend.addBot(req).then(function(res) {
              if (res) {
                my.confirm({
                  title: '温馨提示',
                  content: '添加成功 \n',
                });
              }
            });

          }
        } else {
          // 非调用aibot的消息，存到后端数据库中
          var req = {
            groupOrOwn: 0,
            content: me.data.userMessage,
            contentType: 0,
            groupId: this.getSendToParam(), 
            userId: this.data.username.myName
          };
          backend.sendMessage(req).then(function(res) {
            console.log("发送消息结果: ", res);
          });
        }
        
      } else {
        // 单聊
        if (this.getSendToParam() == 'user_bot') {
          if (curInputMessage.startsWith('/list')) {
            backend.promptList().then(function(res) {
              var promptList = res;
              var prompts = '';
              // console.log("asd :" + JSON.parse(res));
              for (let i = 0; i < promptList.length; i++) {
                prompts += promptList[i].id + " : " + promptList[i].description + '\n';
              }
              my.confirm({
                title: '模型列表',
                content: prompts,
              });
            });
          } else if (curInputMessage.startsWith('/use')) {
            this.data.promptId = curInputMessage.substring(5);
            console.log("promptId ", this.data.promptId);
          } else if (curInputMessage.startsWith('/ask')) {
            var req = {
              msg: curInputMessage.substring(5),
              promptId: this.data.promptId,
              chatId: '',
              toUserId: this.data.username.myName
            };
            backend.askBot(req);
          }
        }
      }
    

      //
      this.setData({
        userMessage: "",
        inputMessage: ""
      });
    },
    antmoveAction: function () {
      //执行时动态赋值，请勿删除
    }
  },
  // lifetimes
  created() {},
  attached() {},
  moved() {},
  detached() {},
  ready() {}
});